package user.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import commons.ResultBean;
import commons.SmsUtils;
import entity.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import user.service.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/userInfo")
public class UserInfoController {

    @Autowired
    private IUserInfoService iUserInfoService;

    @Autowired
    private ISelectedService iSelectedService;

    @Autowired
    private ITEssential itEssential;

    @Autowired
    private ICredit iCredit;

    @Autowired
    private ICreditCardTypeService typeService;

    @Autowired
    private StringRedisTemplate template;

    @RequestMapping("/user")
    public String getUser(){
        return "user";
    }

    //根据Id查询用户,及卡信息
    @RequestMapping("/getUserById")
    public String getUserById(Long cardnum, Model model, HttpServletRequest request){
        Integer userId =  Integer.parseInt((String)request.getSession().getAttribute("userid"));
        model.addAttribute("user",iUserInfoService.getUserById(userId));
        CcmsCredit credit = iCredit.getCredit(cardnum,request);
        String creditId = template.opsForValue().get("creditId"+userId);
        if (creditId == null){
            template.opsForValue().set("creditId"+userId,credit.getCreditId()+"");
        }else {
            template.opsForValue().getAndSet("creditId"+userId,credit.getCreditId()+"");
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");//设置日期格式
        String format = df.format(new Date());// new Date()为获取当前系统时间
        credit.setRepayment(format+"-"+credit.getRepayment());
        model.addAttribute("credit",credit);
        model.addAttribute("creditType",typeService.getType(credit.getCreditType()));
        return "creditItem";
    }

    @ResponseBody
    @RequestMapping("/uapdateBillType")
    //修改账单类型
    public CcmsUserInfo updateUser(String billType,HttpServletRequest request){
        return iUserInfoService.updateUser(billType,request);
    }

    @ResponseBody
    @RequestMapping("/uapdateAuto")
    //开通或关闭自动还款
    public CcmsUserInfo updataAuto(HttpServletRequest request){
        return iUserInfoService.updateAuto(request);
    }

    @RequestMapping("/edit")
    @ApiOperation(value = "查询用户基本信息并,跳转到用户修改页面")
    public String editUser(HttpServletRequest request,Model model){
        String userid = (String) request.getSession().getAttribute("userid");
        Integer uId = Integer.valueOf(userid);
        String phoneNum = iUserInfoService.getUserPhoneById(uId);
        //System.out.println(phoneNum);
        TEssential tEssential = itEssential.getEssentialByUserId(uId);
        model.addAttribute("phoneNum",phoneNum);
        model.addAttribute("tEssential",tEssential);
        return "edit";
    }

    /**
     * 修改用户基本信息
     * @param request
     * @param cityid
     * @param house
     * @param postnum
     * @return
     */
    @RequestMapping("/editInformation")
    @ResponseBody
    @ApiOperation(value = "修改用户基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cityid",value = "城市ID",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "house",value = "住房信息",required = true,dataType = "String"),
            @ApiImplicitParam(name = "postnum",value = "邮政编码",required = true,dataType = "Integer"),
            @ApiImplicitParam(name = "essentialid",value = "基本信息ID",required = true,dataType = "Integer")
    })
    public ResultBean editInformation(HttpServletRequest request,Integer cityid,String house,Integer postnum,Integer essentialid){
        String userid = (String) request.getSession().getAttribute("userid");
        Integer uId = Integer.valueOf(userid);
        ResultBean resultBean = itEssential.updateInformation(uId,cityid,house,postnum,essentialid);
        return resultBean;
    }

    @RequestMapping("/sendCode")
    @ResponseBody
    @ApiOperation(value = "发送验证码")
    @ApiImplicitParam(name = "phoneNum",value = "电话号码",required = true,dataType = "String")
    public ResultBean sendCode(HttpServletRequest request,String phoneNum) throws ClientException {
        //获取session中的用户ID
        String userid = (String) request.getSession().getAttribute("userid");
        //发送验证码
        Map map = SmsUtils.sendSms(phoneNum);
        SendSmsResponse response = (SendSmsResponse) map.get("response");
        //获取验证码
        String code = (String) map.get("code");
        ResultBean resultBean = new ResultBean();
        if (response.getCode()!= null && response.getCode().equals("OK")){
            template.opsForValue().set("user:"+userid+":"+phoneNum,code,5, TimeUnit.MINUTES);
            resultBean.setCode(200);
            resultBean.setMessage("短信发送成功");
        }else {
            resultBean.setCode(-1);
            resultBean.setMessage("短信发送失败");
        }
        return resultBean;
    }

    @PostMapping("/editPhone")
    @ResponseBody
    @ApiOperation(value = "修改电话号码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phoneNum",value = "电话号码",required = true,dataType = "String"),
            @ApiImplicitParam(name = "code",value = "验证码",required = true,dataType = "String")
    })
    public ResultBean editPhone(HttpServletRequest request,String phoneNum,String code){
        String userid = (String) request.getSession().getAttribute("userid");
        Integer uId = Integer.valueOf(userid);
        //存储在redis中的验证码
        String phoneCode = template.opsForValue().get("user:" + userid + ":" + phoneNum);
        ResultBean resultBean = new ResultBean();
        if (null != phoneCode && !"".equals(phoneCode)){
            if (phoneCode.equals(code)){
                //进行修改
                int result = iUserInfoService.updateUserPhone(uId,phoneNum);
                if (result > 0){
                    resultBean.setCode(200);
                    resultBean.setMessage("修改手机号成功");
                }else {
                    resultBean.setCode(-1);
                    resultBean.setMessage("修改失败");
                }
            }
        }else {
            resultBean.setCode(-1);
            resultBean.setMessage("验证码错误");
        }
        return resultBean;
    }

    @ApiOperation(value = "获取城市列表以及该用户相对应的城市")
    @GetMapping("/editCity")
    @ResponseBody
    public List<CcmsCity> editCity() {
        return iSelectedService.editCity();
    }

    /**
     * 修改密码
     * @param request
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @PostMapping("/editPwd")
    @ResponseBody
    @ApiOperation(value = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPwd",value = "旧的密码",required = true,dataType = "String"),
            @ApiImplicitParam(name = "newPwd",value = "新的密码",required = true,dataType = "String")
    })
    public ResultBean editPwd(HttpServletRequest request,String oldPwd,String newPwd){
        String userid = (String) request.getSession().getAttribute("userid");
        ResultBean resultBean = iUserInfoService.editPwd(userid, oldPwd, newPwd);
        return resultBean;
    }

}
